package fu.k4c.vTeam.ViewDetails;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import fu.k4c.vTeam.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import fu.k4c.vTeam.Main.BaseActivity;
import fu.k4c.vTeam.Object.ItemImage;
import fu.k4c.vTeam.Object.ReturnUpimg;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class ImageActivity extends BaseActivity {
	private DisplayImageOptions options;
	String PlaceID;
	Bundle data;
	String email;
	String createBy;
	String encoded;
	GridView gridView;
	static final private int CHOOSE_VIEW = 11;
	String formatImage;
	private final int SELECT_PHOTO = 111;
	int CURRENT_TAG = 0;
	static final int TAG_GUEST = 0;
	static final int TAG_USER = 1;
	String[] imageUrls;
	List<ItemImage> ListImage;
	String[] idImageUrls;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_image_view);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.stub_image)
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheInMemory().cacheOnDisc().build();
		data = getIntent().getExtras();
		gridView = (GridView) findViewById(R.id.gv_image_view);
		if (data != null) {
			PlaceID = data.getString("IDofItemRevision");
			email = data.getString("email");
			createBy = data.getString("createby");

			if (email.equals("Guest")) {
				CURRENT_TAG = TAG_GUEST;
			} else {
				CURRENT_TAG = TAG_USER;
			}
		}
		getImage();
		if (ListImage.size() != 0) {
			imageUrls = new String[ListImage.size()];
			idImageUrls = new String[ListImage.size()];
			for (int i = 0; i < ListImage.size(); i++) {
				if (ListImage.get(i).getImage().toLowerCase()
						.indexOf("http://") >= 0) {
					imageUrls[i] = ListImage.get(i).getImage();
					idImageUrls[i] = ListImage.get(i).getIdImage();
				} else {
					imageUrls[i] = getString(R.string.connectionString)
							+ ListImage.get(i).getImage();
					idImageUrls[i] = ListImage.get(i).getIdImage();
				}

			}
			gridView.setAdapter(new ImageAdapter());
			gridView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					startImageGalleryActivity(position);
				}
			});
		}

		Button btn_upload = (Button) findViewById(R.id.btn_view_tab_place_details_image);
		btn_upload.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (CURRENT_TAG == TAG_GUEST) {
					Toast.makeText(getApplicationContext(),
							"Đăng nhập để sử dụng chức năng này!",
							Toast.LENGTH_LONG).show();
				} else {
					Intent photoPickerIntent = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					// photoPickerIntent.setType("image/*");
					startActivityForResult(photoPickerIntent, SELECT_PHOTO);
				}
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent imageReturnedIntent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
		if (resultCode == RESULT_OK && requestCode == SELECT_PHOTO) {
			Uri selectedImage = imageReturnedIntent.getData();

			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String filePath = cursor.getString(columnIndex);
			cursor.close();
			File file = new File(filePath);
			if (file.length() > 3145728) {
				Toast.makeText(getApplicationContext(),
						"Ảnh tải lên không quá 3Mb", Toast.LENGTH_LONG).show();
			} else {
				Bitmap yourSelectedImage = decodeFile(file);
				// ImageView imv = (ImageView)findViewById(R.id.te);
				// int abc = yourSelectedImage.getRowBytes() *
				// yourSelectedImage.getHeight();

				String formatimg = GetMimeType(getApplicationContext(),
						selectedImage);
				if (formatimg.equals("image/jpeg")) {
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 100,
							baos); // bm is the bitmap object
					byte[] b = baos.toByteArray();
					encoded = Base64.encodeToString(b, Base64.DEFAULT);
					formatImage = "jpg";
				} else if (formatimg.equals("image/png")) {
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100,
							baos); // bm is the bitmap object
					byte[] b = baos.toByteArray();
					encoded = Base64.encodeToString(b, Base64.DEFAULT);
					formatImage = "png";
				}
				try {
					SchemeRegistry registry = new SchemeRegistry();
					registry.register(new Scheme("http", PlainSocketFactory
							.getSocketFactory(), 80));
					HttpParams httpParams = new BasicHttpParams();
					ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
							httpParams, registry);
					HttpClient client = new DefaultHttpClient(connMgr,
							httpParams);
					HttpPost post = new HttpPost(
							getString(R.string.connectionString)
									+ "vLocationService/Upimg");
					post.setHeader("Accept", "application/text");
					post.setHeader("Content-type", "application/text");
					HashMap<String, Object> postParameters = new HashMap<String, Object>();
					Gson gson = new Gson();
					String jsonParameters = "'" + email + "','" + encoded
							+ "','" + formatImage + "','" + PlaceID + "'";
					// Toast.makeText(getApplicationContext(), jsonParameters,
					// Toast.LENGTH_LONG).show();
					post.setEntity(new StringEntity(jsonParameters));
					HttpResponse response = client.execute(post);
					HttpEntity entity = response.getEntity();
					String jsonresult = EntityUtils.toString(entity);
					// Toast.makeText(getApplicationContext(), jsonresult,
					// Toast.LENGTH_LONG).show();
					ReturnUpimg statusUpload = gson.fromJson(jsonresult,
							ReturnUpimg.class);
					if (statusUpload.getReturnupimg().equals("True")) {
						getImage();
						imageUrls = new String[ListImage.size()];
						idImageUrls = new String[ListImage.size()];
						for (int i = 0; i < ListImage.size(); i++) {
							if (ListImage.get(i).getImage().toLowerCase()
									.indexOf("http://") >= 0) {
								imageUrls[i] = ListImage.get(i).getImage();
								idImageUrls[i] = ListImage.get(i).getIdImage();
							} else {
								imageUrls[i] = getString(R.string.connectionString)
										+ ListImage.get(i).getImage();
								idImageUrls[i] = ListImage.get(i).getIdImage();
							}

						}

						gridView.setAdapter(new ImageAdapter());
						gridView.setOnItemClickListener(new OnItemClickListener() {
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								startImageGalleryActivity(position);
							}
						});
						Toast.makeText(getApplicationContext(),
								"Tải ảnh thành công!", Toast.LENGTH_LONG)
								.show();
					} else {
						Toast.makeText(getApplicationContext(),
								"Tải ảnh thất bại!"+jsonresult, Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.toString(),
							Toast.LENGTH_LONG).show();
				}
			}

		} else if (resultCode == RESULT_OK && requestCode == CHOOSE_VIEW) {
			System.out.println("aaaa");
			getImage();
			imageUrls = new String[ListImage.size()];
			idImageUrls = new String[ListImage.size()];
			for (int i = 0; i < ListImage.size(); i++) {
				if (ListImage.get(i).getImage().toLowerCase()
						.indexOf("http://") >= 0) {
					imageUrls[i] = ListImage.get(i).getImage();
					idImageUrls[i] = ListImage.get(i).getIdImage();
				} else {
					imageUrls[i] = getString(R.string.connectionString)
							+ ListImage.get(i).getImage();
					idImageUrls[i] = ListImage.get(i).getIdImage();
				}

			}

			gridView.setAdapter(new ImageAdapter());
			gridView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					startImageGalleryActivity(position);
				}
			});
		}
		if (requestCode == RESULT_CANCELED) {

		}
	}

	private void startImageGalleryActivity(int position) {
		Intent intent = new Intent(this, ImagePagerActivity.class);
		intent.putExtra("imageURL", imageUrls);
		intent.putExtra("position", position);
		intent.putExtra("id", idImageUrls);
		intent.putExtra("email", email);
		intent.putExtra("createBy", createBy);
		startActivityForResult(intent, CHOOSE_VIEW);
	}

	public class ImageAdapter extends BaseAdapter {
		public int getCount() {
			return imageUrls.length;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final ImageView imageView;
			if (convertView == null) {
				imageView = (ImageView) getLayoutInflater().inflate(
						R.layout.item_grid_image, parent, false);
			} else {
				imageView = (ImageView) convertView;
			}

			imageLoader.displayImage(imageUrls[position], imageView, options,
					new SimpleImageLoadingListener() {

						public void onLoadingComplete(Bitmap loadedImage) {
							Animation anim = AnimationUtils.loadAnimation(
									ImageActivity.this, R.anim.fade_in);
							imageView.setAnimation(anim);
							anim.start();
						}
					});

			return imageView;
		}
	}

	public void getImage() {
		try {
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			HttpParams httpParams = new BasicHttpParams();
			ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
					httpParams, registry);
			HttpClient client = new DefaultHttpClient(connMgr, httpParams);
			HttpPost post = new HttpPost(getString(R.string.connectionString)
					+ "vLocationService/loadAllImage");
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-type", "application/json");
			HashMap<String, Object> postParameters = new HashMap<String, Object>();
			postParameters.put("ItemID", PlaceID);
			Gson gson = new Gson();
			String jsonParameters = gson.toJson(postParameters);
			post.setEntity(new StringEntity(jsonParameters));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String jsonresult = EntityUtils.toString(entity);
			// Toast.makeText(getApplicationContext(), jsonresult,
			// Toast.LENGTH_LONG).show();
			Type listType = (Type) new TypeToken<ArrayList<ItemImage>>() {
			}.getType();
			ListImage = gson.fromJson(jsonresult, listType);
			// Toast.makeText(getApplicationContext(), ListImage.size() +
			// " haiz", Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static String GetMimeType(Context context, Uri uriImage) {
		String strMimeType = null;

		Cursor cursor = context.getContentResolver().query(uriImage,
				new String[] { MediaStore.MediaColumns.MIME_TYPE }, null, null,
				null);

		if (cursor != null && cursor.moveToNext()) {
			strMimeType = cursor.getString(0);
		}

		return strMimeType;
	}

	private Bitmap decodeFile(File f) {
		try {
			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// The new size we want to scale to
			final int REQUIRED_SIZE = 70;

			// Find the correct scale value. It should be the power of 2.
			int scale = 1;
			while (o.outWidth / scale / 2 >= REQUIRED_SIZE
					&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
				scale *= 2;

			// Decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

}
